package com.pikaqiu.demo.controller;

import com.alibaba.fastjson.JSONObject;
import com.pikaqiu.demo.service.WeChatService;
import com.pikaqiu.demo.utils.WeChatMessageUtil;
import com.pikaqiu.demo.utils.WeChatUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Map;

/**
 * @author 吕梁山
 * @date 2019/4/22
 */
@RestController
@RequestMapping(value = "/wechat")
public class WeChatController {

    private Logger logger = LoggerFactory.getLogger(WeChatController.class);

    @Resource
    private WeChatService weChatService;

    @Resource
    private WeChatUtil weChatUtil;

    @RequestMapping(value="", method = RequestMethod.GET)
    public String index(HttpServletRequest request) {
        logger.info("进入验签");
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");
        boolean b = weChatUtil.checkSignature(signature, timestamp, nonce);
        return b ? echostr : "";
    }

    @RequestMapping(value="", method = RequestMethod.POST)
    public String getWeiXinMessage(HttpServletRequest request)throws Exception {
        Map<String, String> map = WeChatMessageUtil.xmlToMap(request);
        logger.info("用户发送消息：" + map.toString());
        return weChatService.returnMessage(map);
    }

    @RequestMapping(value="/authorize")
    public JSONObject authorize(String href) throws Exception {
        String redirectUrl = WeChatUtil.URL_OAUTH2_AUTHRIZE;
        redirectUrl = redirectUrl.replaceAll("APPID", WeChatUtil.APP_ID);
        redirectUrl = redirectUrl.replaceAll("REDIRECT_URI", URLEncoder.encode(href, "UTF-8"));
        redirectUrl = redirectUrl.replaceAll("SCOPE", "snsapi_userinfo");
        redirectUrl = redirectUrl.replaceAll("STATE", "1");
        logger.info("获取网页授权URL:{}", redirectUrl);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("url", redirectUrl);
        return jsonObject;
    }

    @RequestMapping(value="/getWebConfig")
    public JSONObject getWebConfig(String url) throws IOException {
        JSONObject jsonObject = new JSONObject();
        long time = new Date().getTime();
        jsonObject.put("appId", WeChatUtil.APP_ID);
        jsonObject.put("timestamp", time);
        jsonObject.put("nonceStr", time + "");
        jsonObject.put("signature", weChatUtil.getJsapiTicketSign(time + "", time, url));
        return jsonObject;
    }

}